<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script type="text/javascript">
        var ws;


        function WebSocketTest()
        {
            if ("WebSocket" in window)
            {
                var username = document.getElementById("username").value;
                // 打开一个 web socket
                ws = new WebSocket("ws://localhost:8080/websocket/"+username);

                ws.onopen = function()
                {
                    fillData("连接成功");

                };

                ws.onmessage = function (evt)
                {
                    var received_msg = evt.data;
                    fillData(received_msg);
                };

                ws.onclose = function()
                {
                    fillData("连接关闭")
                };

            }

            else
            {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
            }
        }

        //向contents中插入数据
        function fillData(data) {
            document.getElementById("contents").innerHTML = data;
        }


        //发送数据
        function sendmsg() {
            var msg = document.getElementById("msginfo").value;
            var tousername = document.getElementById("tousername").value;
            var mssage='{"toUser":"'+tousername+'","msg":"'+msg+'"}';
            ws.send(mssage);
        }


        //连接关闭
        function closewebsocket() {
            if (ws){
                ws.close();
            }
            
        }


    </script>
</head>
<body>

    姓名:<input id="username">
    <button onclick="WebSocketTest()">连接</button>
    <br/>
    <br/>

    对方姓名:<input id="tousername">
    <br/>
    <br/>

    消息内容:<textarea id="msginfo"></textarea>
    <button onclick="sendmsg()">发送</button>
    <br/>
    <br/>
    <button onclick="closewebsocket()">断开连接</button>
    <br/>
    <br/>
    <br/>
    <br/>
    <span id="contents"></span>



</body>
</html>